<!DOCTYPE html>
<html lang="en">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/zezhang/img/favicon.webp">
  <link rel="icon" type="image/png" href="/zezhang/img/favicon.webp">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="ZeZhang">
  <meta name="keywords" content="">
  <title>this指向问题 - 你那里天气还好吗?</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/zezhang/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/github-gist.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/zezhang/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/zezhang/js/utils.js" ></script>
<meta name="generator" content="Hexo 4.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/zezhang/">&nbsp;<strong>你那里天气还好吗?</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/zezhang/">
                <i class="iconfont icon-home-fill"></i>
                Home
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/zezhang/archives/">
                <i class="iconfont icon-archive-fill"></i>
                Archives
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/zezhang/tags/">
                <i class="iconfont icon-tags-fill"></i>
                Tags
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/zezhang/about/">
                <i class="iconfont icon-user-fill"></i>
                About
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/zezhang/img/banner8.webp') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2020-03-09 12:27">
      March 9, 2020 pm
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      689 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      9
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
            <article class="markdown-body">
              <h3 id="this的作用"><a href="#this的作用" class="headerlink" title="this的作用"></a>this的作用</h3><ul>
<li>this可以帮我们简化很多代码。比如<code>xiaoming.name</code>、<code>xiaoming.age</code>可以直接写成<code>this.name</code>、<code>this.age</code>。</li>
<li>特别是当我们不知道一个对象是什么，或者这个对象没有名字但又很想调用它的时候，就会使用到this对象。</li>
<li><a id="more"></a>

</li>
</ul>
<p><strong>举例：</strong></p>
<ul>
<li>遍历DOM对象，绑定click事件，调用当前点击的对象的id，而不是所有对象的id。</li>
</ul>
<p>代码：</p>
<pre><code class="hljs html">&lt;!doctype html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport"
    &lt;title&gt;Document&lt;/title&gt;
    &lt;style&gt;
        div &#123;
            width: 100px;
            height: 100px;
            background-color: green;
            margin: 10px;
        &#125;

    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;script&gt;
    window.onload = function () &#123;
        var myDiv = document.getElementsByTagName('div');
        for (var i = 0; i &lt; myDiv.length; i++) &#123;
            myDiv[i].onclick = function () &#123;
                console.log(i);
                console.log(this.id);
            &#125;
        &#125;

    &#125;

&lt;/script&gt;
&lt;section&gt;
    &lt;div id="div0"&gt; div0&lt;/div&gt;
    &lt;div id="div1"&gt; div1&lt;/div&gt;
    &lt;div id="div2"&gt; div2&lt;/div&gt;
    &lt;div id="div3"&gt; div3&lt;/div&gt;
    &lt;div id="div4"&gt; div4&lt;/div&gt;
&lt;/section&gt;


&lt;/body&gt;
&lt;/html&gt;</code></pre>


<p>点击其中的任何一个元素后，<code>i</code>的打印结果是5。你可能会觉得很惊讶。我们来解释一下：</p>
<p>当代码执行完毕后，i已经等于5了。因为一旦运行程序，for循环已经执行完了，此时i等于5。</p>
<p>现在，我们尝试在 myDiv[i].onclick事件中写代码，如果打印：</p>
<pre><code class="hljs 1c">console.<span class="hljs-built_in">log</span>(i);  <span class="hljs-comment">//打印结果为5</span></code></pre>


<p>如果打印：</p>
<pre><code class="hljs css"><span class="hljs-selector-tag">console</span><span class="hljs-selector-class">.log</span>(<span class="hljs-selector-tag">myDiv</span><span class="hljs-selector-attr">[i]</span><span class="hljs-selector-class">.id</span>);</code></pre>

<p>上方这行代码，打印会报错，因为i=5；如果想打印每个div的id，应该这样写：</p>
<pre><code class="hljs applescript">console.<span class="hljs-built_in">log</span>(this.<span class="hljs-built_in">id</span>);</code></pre>

<p>你看，this的作用，就体现出来了。</p>
<p>PS：顺便提醒一下，上面的代码中，如果把<code>var i</code>改成<code>let i</code>，效果又完全不同了。参考链接：<a href="http://blog.csdn.net/stopllL/article/details/64130664" target="_blank" rel="noopener">let和var在for循环中的表现</a></p>
<h3 id="全局作用域中的this"><a href="#全局作用域中的this" class="headerlink" title="全局作用域中的this"></a>全局作用域中的this</h3><p>当一段代码在浏览器中执行时，所有的全局变量和对象都是在window对象上定义的。换而言之，所有的全局变量和对象都属于window对象。</p>
<h2 id="this的定律"><a href="#this的定律" class="headerlink" title="this的定律"></a>this的定律</h2><p>this关键字永远指向函数（方法）运行时的<strong>所有者</strong>。</p>
<h3 id="函数赋值给变量时，this指向window"><a href="#函数赋值给变量时，this指向window" class="headerlink" title="函数赋值给变量时，this指向window"></a>函数赋值给变量时，this指向window</h3><p>比如：</p>
<pre><code class="hljs actionscript"><span class="hljs-keyword">var</span> foo1 = args.getInfo;
foo1();

<span class="hljs-keyword">var</span> foo2 = <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">()</span></span>&#123;&#125;;
foo2();</code></pre>


<p>this都是指向window。</p>
<h3 id="以函数形式调用时，this永远都是window"><a href="#以函数形式调用时，this永远都是window" class="headerlink" title="以函数形式调用时，this永远都是window"></a>以函数形式调用时，this永远都是window</h3><h3 id="以方法的形式调用时，this是调用方法的对象"><a href="#以方法的形式调用时，this是调用方法的对象" class="headerlink" title="以方法的形式调用时，this是调用方法的对象"></a>以方法的形式调用时，this是调用方法的对象</h3><h2 id="解决闭包中的this指向问题"><a href="#解决闭包中的this指向问题" class="headerlink" title="解决闭包中的this指向问题"></a>解决闭包中的this指向问题</h2><p>内部函数是可以访问到外部函数的变量的。</p>
<p>方式一：直接通过父函数的名字访问</p>
<p>方式二：如果不知道父函数的名字，在父函数里加一句<code>_this = this</code>，此时<code>_this</code>相当于父函数的名字。</p>
<h3 id="当this遇到一些特殊的函数时"><a href="#当this遇到一些特殊的函数时" class="headerlink" title="当this遇到一些特殊的函数时"></a>当this遇到一些特殊的函数时</h3>
            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/zezhang/tags/JavaScript/">JavaScript</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/zezhang/2020/03/11/%E6%95%B0%E7%BB%84%E5%B8%B8%E7%94%A8%E6%93%8D%E4%BD%9C/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">数组常用操作(含ES6)</span>
                        <span class="visible-mobile">Previous</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/zezhang/2020/02/01/%E5%9E%82%E7%9B%B4%E5%B1%85%E4%B8%AD%E7%9A%84N%E7%A7%8D%E5%8A%9E%E6%B3%95/">
                        <span class="hidden-mobile">垂直居中的N种办法</span>
                        <span class="visible-mobile">Next</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;TOC</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">Search</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">keyword</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/zezhang/js/debouncer.js" ></script>
<script  src="/zezhang/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/zezhang/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/zezhang/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "this指向问题&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/zezhang/js/local-search.js" ></script>
  <script>
    var path = "/zezhang/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>




















</body>
</html>
